package com.zxj.hadoop.demo.mapreduce.findfriend;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

/**
 * @Author 朱小杰
 * 时间 2017-08-24 .22:59
 * 说明 先算出某个用户是哪些人的好友
 */
public class Friend1 {


    static class FriendMapper1 extends Mapper<LongWritable, Text, Text, Text> {
        private Text k = new Text();
        private Text v = new Text();
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String line = value.toString();
            String[] personFriends = line.split(":");
            String person = personFriends[0];//用户
            String friends = personFriends[1];//好友
            for (String friend : friends.split(",")) {
                //输出<好友，人>
                k.set(friend);
                v.set(person);
                context.write(k,v);
            }
        }
    }

    /**
     * 输入 好友，用户
     */
    static class FriendReduce1 extends Reducer<Text,Text,Text,Text>{
        private Text k = new Text();
        private Text v = new Text();
        @Override
        protected void reduce(Text friend, Iterable<Text> persons, Context context) throws IOException, InterruptedException {
            StringBuffer sb = new StringBuffer();
            for(Text person : persons){
                sb.append(person).append(",");
            }
            k.set(friend);
            v.set(sb.toString());
            context.write(k,v);
        }
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        String input = "D:\\mr\\qq\\input";
        String output = "D:\\mr\\qq\\out1";
        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf);

        job.setJarByClass(Friend1.class);

        job.setMapperClass(FriendMapper1.class);
        job.setReducerClass(FriendReduce1.class);

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(Text.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);

        FileInputFormat.setInputPaths(job,new Path(input));
        FileOutputFormat.setOutputPath(job,new Path(output));

        boolean b = job.waitForCompletion(true);
        if(b){}

    }
}
